namespace :block do
  # rake block:change_top10
  desc "change_top10"
  task :change_top10, [:name] => :environment do |t, args|
    puts "【block:change_top10】#{Time.now} start"
    name = args[:name]
    # 查询板块
    block = Block.find_by(name: name)
    # block.stocks.each do |stock|
    #   ts_code = stock.ts_code
    #   daily = $TusharePro.tushare_pro("daily", ts_code: ts_code, start_date: trade_date(20), end_date: Time.now.strftime("%Y%m%d"))
    #   next if daily.blank?
    #   change = ((daily[1]["close"].to_f - daily[-1]["close"].to_f) * 100 / daily[-1]["close"].to_f).round(2)
    #   puts "#{ts_code} -- #{change}%"
    # rescue StandardError => e
    #   puts "Error processing #{ts_code}: #{e.message}"
    # end

    trade_date_20 = trade_date(20) # 获取20个交易日前的日期
    debugger
    stock_klines = Parallel.map(block.stocks, in_processes: 8, progress: true) do |stock|
      kline = Tushare::Stock::Trading.get_k_data(stock.symbol, "#{trade_date_20[0..3]}-#{trade_date_20[4..5]}-#{trade_date_20[6..7]}", Time.now.strftime("%Y-%m-%d"))
      next if kline.empty?
      k_line_10 = kline.last 10
      puts "#{stock.name} -- #{stock.symbol} -- #{k_line_10.first["close"]} -- #{k_line_10.last["close"]} -- #{k_line_10.first["date"]} -- #{k_line_10.last["date"]}"
      puts "#{stock.name} -- #{stock.symbol} -- #{kline.pluck("low").min} -- #{kline.pluck("high").max} -- #{kline.first["date"]} -- #{kline.last["date"]}"
      { name: stock.name, symbol: stock.symbol, change_10: cul_change(k_line_10.first["close"], k_line_10.last["close"]), ths_flow: stock.ths_flow, year_count: stock.year_count, is_buy_point: stock.is_buy_point, amplitude: cul_change(kline.pluck("low").min, kline.pluck("high").max) }
    end
    stocks_charts = stock_klines.compact.sort_by { |x| x[:change_10] }.reverse.first(10)
    puts "【block:change_top10】#{Time.now} end"
  end

  # rake block:start_end_time_block_ranks['20251017','20251104']
  desc "start_end_time_block_ranks"
  task :start_end_time_block_ranks, [:start_date, :end_date] => :environment do |t, args|
    # 时间周期内全部板块涨幅和振幅排行
    puts "【block:start_end_time_block_ranks】#{Time.now} start"
    start_date = args[:start_date]
    end_date = args[:end_date]
    puts "统计周期： #{start_date} -- #{end_date}"
    # ths_indexes = $TusharePro.tushare_pro("ths_index", exchange: "A", type: "N").first(10)
    ths_indexes = $TusharePro.tushare_pro("ths_index", exchange: "A", type: "N")
    ths_dailies = []
    ths_indexes.each do |ths_index|
      ths_daily = $TusharePro.tushare_pro("ths_daily", ts_code: ths_index["ts_code"], start_date: start_date, end_date: end_date)
      next if ths_daily.blank?
      close = ths_daily.first["close"].to_f
      open = ths_daily.last["open"].to_f
      change = cul_change(open, close)

      delay_millisecond(1, 200) {}
      ths_daily_max = ths_daily.pluck("high").max
      ths_daily_min = ths_daily.pluck("low").min
      amplitude = cul_change(ths_daily_min, ths_daily_max)
      hash = { name: ths_index["name"], ts_code: ths_index["ts_code"], amplitude: amplitude, change: change, pct_change: ths_daily.pluck("pct_change").map { |x| x.round(2) } }
      ths_dailies << hash
    end
    puts "amplitude 排行"
    ths_dailies.sort_by { |x| x[:amplitude] }.reverse.each_with_index do |ths_daily, index|
      File.open "block:start_end_time_block_ranks#{start_date}——#{end_date}.txt", "a" do |f|
        f.puts "#{index + 1} -- #{ths_daily[:name]} -- #{ths_daily[:ts_code]} -- #{ths_daily[:amplitude]}% -- #{ths_daily[:change]}% -- #{ths_daily[:pct_change].join(",")}"
      end
      puts "#{index + 1} -- #{ths_daily[:name]} -- #{ths_daily[:ts_code]} -- #{ths_daily[:amplitude]}% -- #{ths_daily[:change]}% -- #{ths_daily[:pct_change].join(",")}"
    end
    puts "---------------------------------------------------------------------------------------------------------"
    puts "---------------------------------------------------------------------------------------------------------"
    puts "change 排行"
    ths_dailies.sort_by { |x| x[:change] }.reverse.each_with_index do |ths_daily, index|
      File.open "block:start_end_time_block_ranks#{start_date}——#{end_date}.txt", "a" do |f|
        f.puts "#{index + 1} -- #{ths_daily[:name]} -- #{ths_daily[:ts_code]} -- #{ths_daily[:change]}% -- #{ths_daily[:amplitude]}% -- #{ths_daily[:pct_change].join(",")}"
      end
      puts "#{index + 1} -- #{ths_daily[:name]} -- #{ths_daily[:ts_code]} -- #{ths_daily[:change]}% -- #{ths_daily[:amplitude]}% -- #{ths_daily[:pct_change].join(",")}"
    end

    puts "【block:start_end_time_block_ranks】#{Time.now} end"
  end

  # 跟随大盘，超越大盘的板块
  # rake block:follow_market_block_ranks
  desc "follow_market_block_ranks"
  task :follow_market_block_ranks, [:name] => :environment do |t, args|
    puts "【block:follow_market_block_ranks】#{Time.now} start"
    puts start_date = trade_date(5)
    end_date = trade_date(1)
    # 大盘指数
    index_daily = $TusharePro.tushare_pro("index_daily", ts_code: "000001.SH", start_date: start_date, end_date: end_date)
    ths_indexes = $TusharePro.tushare_pro("ths_index", exchange: "A", type: "N")
    ths_indexes.each do |ths_index|
      ths_daily = $TusharePro.tushare_pro("ths_daily", ts_code: ths_index["ts_code"], start_date: start_date, end_date: end_date)
      delay_millisecond(1, 200) {}
      next if ths_daily.blank?
      ths_daily.each do |block|
        index_pct_change = index_daily.select { |x| x["trade_date"] == block["trade_date"] }.first["pct_chg"].to_f.round(2)
        block_pct_change = block["pct_change"].to_f.round(2)
        if (block_pct_change < index_pct_change && block_pct_change < 0) || (block_pct_change > index_pct_change && block_pct_change > 0)

        end
      end
      puts "#{ths_index['name']} -- #{ths_index['ts_code']}"
    end
    puts "【block:follow_market_block_ranks】#{Time.now} end"
  end

  # 某板块最近 days 天涨幅超过2%，且成分股涨幅超过4%
  # rake block:latest_days_change_up2['60','885947.TI']
  desc "latest_days_change_up2"
  task :latest_days_change_up2, [:days, :ts_code] => :environment do |t, args|
    days = args[:days]
    ts_code = args[:ts_code]
    $TusharePro.tushare_pro("ths_daily", ts_code: ts_code, start_date: trade_date(days.to_i), end_date: Time.now.strftime("%Y%m%d")).each do |daily|
      next if daily['pct_change'].to_f < 2
      # 查询板块成分股
      members = $TusharePro.tushare_pro("ths_member", "ts_code": ts_code).select { |x| x["con_code"][0..5] < "680000" && x["con_code"][0] != "4" }
      puts "#{daily['trade_date']} -- #{daily['pct_change']} -- #{members.count} 股"
      members.each do |member|
        klines = Tushare::Stock::Trading.get_k_data member["con_code"][0..5]
        if klines.blank?
          next
        end
        kline = klines.select { |x| x["date"] >= "#{daily['trade_date'][0,4]}-#{daily['trade_date'][4,2]}-#{daily['trade_date'][6,2]}" }.first
        change = cul_change(kline["open"], kline["close"])
        next if change < 4
        puts "  #{member['con_name']} -- #{member['con_code']} -- #{change}%"
      end
    end
  end

  # 指定几个板块共同的股票
  # rake block:common_stocks['885879.TI-886015.TI-885769.TI-881140.TI']
  #  desc "common_stocks"
  task :common_stocks, [:ts_codes] => :environment do |t, args|
    ts_codes = args[:ts_codes].split("-")
    blocks_members = ts_codes.map do |ts_code|
      $TusharePro.tushare_pro("ths_member", "ts_code": ts_code).select { |x| x["con_code"][0..5] < "680000" && x["con_code"][0] != "4" }.map { |x| x["con_code"][0..5] }
    end
    common_stocks = blocks_members.reduce(:&) # 取交集
    puts "共同股票 #{common_stocks.count} 股"
    common_stocks.each do |code|
      stock = Stock.find_by(symbol: code)
      ths_flow = RealTime.ths_flow code

      puts "#{stock.name} -- #{stock.symbol} -- #{stock.choice_block_tag} -- #{ths_flow["title"]["je"]} -- #{stock.year_count} -- #{stock.is_buy_point? ? '是' : '否'}"
    end
    puts "【block:common_stocks】#{Time.now} end"
  end
end